/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain (a) copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry.ohos.core;

import ohos.app.Context;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.util.UUID;

/**
 * Installation
 *
 * @since 2021-06-01
 */
public final class Installation {
    @TestOnly
    static @Nullable String deviceId = null;

    @TestOnly
    static final String INSTALLATION = "INSTALLATION";

    private static final Charset UTF_8 = Charset.forName("UTF-8");

    private Installation() {
    }

    /**
     * Generates (a) random UUID and writes to (a) file to be used as an unique installationId. Reads the
     * installationId if already exists.
     *
     * @param context the Context
     * @return the generated installationId
     * @throws IOException if not possible to read nor to write to the file.
     */
    public static synchronized String id(final @NotNull Context context) throws IOException {
        if (deviceId == null) {
            final File installation = new File(context.getFilesDir(), INSTALLATION);
            try {
                if (!installation.exists()) {
                    deviceId = writeInstallationFile(installation);
                    return deviceId;
                }
                deviceId = readInstallationFile(installation);
            } catch (Exception e) {
                throw new IOException(e);
            }
        }
        return deviceId;
    }

    /**
     * readInstallationFile
     *
     * @param installation File
     * @return String
     * @throws IOException
     */
    @TestOnly
    public static @NotNull String readInstallationFile(final @NotNull File installation) throws IOException {
        try (RandomAccessFile f = new RandomAccessFile(installation, "r")) {
            final byte[] bytes = new byte[(int) f.length()];
            f.readFully(bytes);
            return new String(bytes, UTF_8);
        }
    }

    /**
     * writeInstallationFile
     *
     * @param installation File
     * @return String
     * @throws IOException
     */
    @TestOnly
    public static @NotNull String writeInstallationFile(final @NotNull File installation)
        throws IOException {
        try (OutputStream out = new FileOutputStream(installation)) {
            final String id = UUID.randomUUID().toString();
            out.write(id.getBytes(UTF_8));
            out.flush();
            return id;
        }
    }
}
